package com.youth.orderservice.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.youth.ClientEntity.OrderCourse;
import com.youth.ClientEntity.UserEntity;
import com.youth.commonutils.R;
import com.youth.commonutils.RedisConstants;
import com.youth.orderservice.Utils.RedisIdWorker;
import com.youth.orderservice.Client.CourseClient;
import com.youth.orderservice.Client.UserClient;
import com.youth.orderservice.entity.OrderVo.OrderQuery;
import com.youth.orderservice.entity.TOrder;
import com.youth.orderservice.mapper.TOrderMapper;
import com.youth.orderservice.mq.entity.info.CreateOrderSimplInfo;
import com.youth.orderservice.service.TOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 订单 服务实现类
 * </p>
 *
 * @author huangqicai
 * @since 2023-04-06
 */
@Service
public class TOrderServiceImpl extends ServiceImpl<TOrderMapper, TOrder> implements TOrderService {

    /*订单序列号生成器*/
    @Autowired
    private RedisIdWorker redisIdWorker;

    @Autowired
    private UserClient userClient;

    @Autowired
    private CourseClient courseClient;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private TOrderMapper tOrderMapper;

    /*根据课程id和用户id去创建订单*/
    @Override
    @Transactional
    public R createOrder(String courseId, String userId) {
        if (userId.isEmpty()) {
            return R.error().code(2).message("用户没有登录");
        }
        /*1.根据用户id和课程id去查询数据库，看是否已经有过该订单信息*/
        TOrder tOrder = baseMapper.selectOne(new QueryWrapper<TOrder>()
                .eq("course_id", courseId)
                .eq("member_id", userId));
        if (tOrder != null) {
            return R.error().code(1).message("你已经创建过该课程的订单信息，请前往支付");
        }
        long orderNo = redisIdWorker.nextId(RedisConstants.ORDER);
        CreateOrderSimplInfo OrderSimpleInfo = new CreateOrderSimplInfo();
        OrderSimpleInfo.setOrderId(String.valueOf(orderNo));
        OrderSimpleInfo.setCourseId(courseId);
        OrderSimpleInfo.setUserId(userId);
        /*2.创建订单*/
        String orderId = createOrderToSql(OrderSimpleInfo);
        System.out.println("创建订单的结果：" + orderId);
        /*3.异步将订单信息发给消息队列*/
        orderInfoToRabbitmq(OrderSimpleInfo);
        if (!StringUtils.isEmpty(orderId)) {
            return R.ok().data("orderId", orderId);
        }
        return null;
    }

    /*创建订单*/
    public String createOrderToSql(CreateOrderSimplInfo orderSimplInfo) {
        HashMap<String, String> map = new HashMap<>();
        map.put("userId", orderSimplInfo.getUserId());
        UserEntity userEntity = userClient.ByIdGetUser(map);
        /*3.根据课程id查询课程信息*/
        OrderCourse orderCourse = courseClient.orderCourse(orderSimplInfo.getCourseId());
        /*4.创建订单*/
        TOrder tOrder = new TOrder();
        /*实体类转换*/
        tOrder.setOrderNo(String.valueOf(orderSimplInfo.getOrderId()));
        if (!StringUtils.isEmpty(orderCourse.getCourseId())) {
            BeanUtils.copyProperties(orderCourse, tOrder);
        }
        if (!StringUtils.isEmpty(userEntity.getId())) {
            BeanUtils.copyProperties(userEntity, tOrder);
            tOrder.setMemberId(userEntity.getId());
        }
        /*设置支付状态*/
        tOrder.setStatus(0);
        System.out.println("订单1111信息：" + JSON.toJSONString(tOrder));
        int insert = baseMapper.insert(tOrder);
        System.out.println("insert的值：" + insert);
        if (insert > 0) {
            return tOrder.getOrderId();
        }
        return null;
    }

    public void orderInfoToRabbitmq(CreateOrderSimplInfo orderSimplInfo) {
        /*创建一个单线程池*/
        ExecutorService executor = Executors.newSingleThreadExecutor();
        Runnable task = new Runnable() {
            @Override
            public void run() {
                /*将消息转化成json格式*/
                String jsonString = JSON.toJSONString(orderSimplInfo);
                /*处理消息*/
                rabbitTemplate.convertAndSend("X", "XA", jsonString);
            }
        };
        executor.submit(task);
    }


    /*根据订单id获取订单信息*/
    @Override
    public R getOrderById(String orderId) {
        TOrder tOrder = baseMapper.selectById(orderId);
        return R.ok().data("tOrder", tOrder);
    }


    /*分页条件查询订单信息*/
    @Override
    public R getPageList(long current, long limit, OrderQuery orderQuery) {
        HashMap<String, Object> map = new HashMap<>();
        if (!StringUtils.isEmpty(orderQuery.getOrderNo())) {
            map.put("orderNo", orderQuery.getOrderNo());
        }
        if (!StringUtils.isEmpty(orderQuery.getNickname())) {
            map.put("nickname", orderQuery.getNickname());
        }

        if (!StringUtils.isEmpty(orderQuery.getMobile())) {
            map.put("mobile", orderQuery.getMobile());
        }

        if (!StringUtils.isEmpty(orderQuery.getTitle())) {
            map.put("title", orderQuery.getTitle());
        }
        IPage<TOrder> tOrderIPage = tOrderMapper.selectListOrders(new Page<>(current, limit), map);
        HashMap<String, Object> mapRes = new HashMap<>();
        mapRes.put("total", tOrderIPage.getTotal());
        mapRes.put("rows", tOrderIPage.getRecords());
        return R.ok().data(mapRes);

    }

    /*根据订单id删除订单信息*/
    @Override
    public R deleteOrder(String orderId) {
        boolean flag = baseMapper.deleteOrder(orderId);
        if (flag) {
            return R.ok();
        }
        return R.error();
    }

    /*根据订单id和订单实体类更新订单信息*/
    @Override
    public R updateOrder(String orderId, TOrder tOrder) {
        int flag = baseMapper.update(tOrder, new QueryWrapper<TOrder>().eq("id", orderId));
        if (flag > 0) {
            return R.ok();
        }
        return R.error();
    }


}
